from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from models import *
from myhotel.forms import RegistrationForm
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
# Create your views here.

def index(request):
    hotels = Hotel.objects.all()
    context = {'hotels': hotels, 'request': request}
    return render(request, 'myhotel/index.html', context)


@csrf_protect
def register(request):
    if request.user.is_authenticated():
        return redirect('/myhotel/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/myhotel/register/success/')
    else:
        form = RegistrationForm()
    return render_to_response('registration/register.html', {'form': form}, context_instance=RequestContext(request))


def register_success(request):
    return render_to_response('registration/success.html', )


def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/myhotel/')


@login_required
def viewHotel(request, h_id):
    if request.method == 'POST':
        myhotel = Hotel.objects.filter(id=h_id)
        x = Review(comment=request.POST.get("comment", ""), hotel=myhotel[0], user=request.user,
                   rating=request.POST.get("rating", ""))
        x.save()
    hotel = Hotel.objects.filter(id=h_id)
    reviews = Review.objects.filter(hotel=h_id).select_related()
    reviewsCount = Review.objects.filter(hotel=h_id).count()
    sum = 0
    for y in reviews:
        sum += y.rating
    rate = sum / reviewsCount
    context = {'hotels': hotel, 'reviews': reviews}
    context['starsOn'] = []
    for i in range(rate):
        context['starsOn'].append(i + 1)
    context['starsOff'] = []
    for i in range(5 - rate):
        context['starsOff'].append(i + 1)
    return render(request, 'myhotel/hotel.html', context)


@login_required
def viewOffers(request, h_id):
    offers = Offer.objects.filter(hotel=h_id).select_related()
    context = {'offers': offers}
    return render(request, 'myhotel/offers.html', context)


@csrf_protect
def checkBook(request, h_id, o_id):
    if request.method == 'POST':
        error = None
        rooms = request.POST.get("number", "")
        start = request.POST.get("start", "")
        end = request.POST.get("end", "")
        startFormat = datetime.datetime.strptime(start, "%Y-%m-%d")
        endFormat = datetime.datetime.strptime(end, "%Y-%m-%d")
        if startFormat > endFormat:
            error = 'Start date of booking can\'t be after booking End date'
        if datetime.datetime.now() > startFormat:
            error = ' :: Start date of booking can\'t be smaller than today'
        if error:
            offers = Offer.objects.filter(hotel=h_id).select_related()
            context = {'offers': offers, 'errors': error}
            return render(request, 'myhotel/offers.html', context)
        else:
            myoffer = Offer.objects.filter(id=o_id).select_related()
            diff = endFormat - startFormat
            number = diff.days
            z = number * myoffer[0].price
            totalPrice = z * int(rooms)
            context = {'myoffer': myoffer[0], 'start': startFormat, 'end': endFormat, 'number': number,
                       'price': totalPrice, 'rooms': rooms}
            return render(request, 'myhotel/confirm.html', context)
        return render(request, 'myhotel/offers.html', )


def confirm(request, o_id):
    if request.method == 'POST':
        myoffer = Offer.objects.filter(id=o_id)
        start=request.POST.get("startdate", "").replace('midnight', '')
        end=request.POST.get("enddate", "").replace('midnight','')
        startformat=datetime.datetime.strptime(start,'%B %d, %Y, ')
        endformat=datetime.datetime.strptime(end,'%B %d, %Y, ')
        x = Book(mystart=startformat, offer=myoffer[0], user=request.user, myend=endformat)
        x.save()
        return render(request, 'myhotel/success.html')